package com.andy.buyu.server.client;

import com.andy.buyu.server.socket.codec.RequestDecoder;
import com.andy.buyu.server.socket.codec.ResponseEncoder;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

public class FishClient {

	private String ip;
	private int port;
	
	public FishClient(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}

	public void connect() throws InterruptedException {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {
					ChannelPipeline pipeline = ch.pipeline();
					pipeline.addLast(new LengthFieldBasedFrameDecoder(1024,0,4,0,4));
					pipeline.addLast("UserDecoder", new RequestDecoder());
					pipeline.addLast("UserEncoder", new ResponseEncoder());
					pipeline.addLast(new FishClientHandler());
				}
			});

			// Start the connection attempt.
			b.connect(ip, port).sync().channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}

}
